package com.oha.laporrayelchurro.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.oha.laporrayelchurro.model.Partido;
import com.oha.laporrayelchurro.service.H2DataBaseService;

public class PartidoDao extends H2BaseDao{
	
	private static Logger log4j = Logger.getLogger(PartidoDao.class);

	public void save(Partido partido){
		String sql ="insert into partido(orden, tipo, hora, grupo, pais1, pais2) values(?, ?,?,?,?,?)";
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			H2DataBaseService dbs = new H2DataBaseService();
			conn =dbs.getConnection();
			pstm = conn.prepareStatement(sql);
			int index=1;
			pstm.setInt(index++, partido.getOrden());
			pstm.setInt(index++, partido.getTipo());
			pstm.setTimestamp(index++, new Timestamp(partido.getHora().getTime()));
			pstm.setString(index++, partido.getGrupo());
			pstm.setString(index++, partido.getPais1());
			pstm.setString(index++, partido.getPais2());
			pstm.executeUpdate();
		} catch (SQLException e) {
			log4j.error("SQLException.save.getP.", e);
		}finally{
			close(pstm);
			close(conn);
		}
	}
	
	/**
	 * elimina la tabla
	 */
	public void resetTable(){
		String sql ="drop table partido";
		String sqlCreate = "create table partido (".concat(
				" idPartido int primary key auto_increment,").concat( 
				" hora timestamp, ").concat(
				" grupo varchar(5), ").concat(
				" orden int,").concat(
				" tipo int,").concat(
				" pais1 varchar(100),").concat(
				" pais2 varchar(100)").concat(
				" )");
		Connection conn = null;
		PreparedStatement pstmDel = null;
		PreparedStatement pstmCreate = null;
		try {
			H2DataBaseService dbs = new H2DataBaseService();
			conn =dbs.getConnection();
			pstmDel = conn.prepareStatement(sql);
			pstmDel.executeUpdate();
			pstmCreate = conn.prepareStatement(sqlCreate);
			pstmCreate.executeUpdate();
		} catch (SQLException e) {
			log4j.error("SQLException.save.getP.", e);
		}finally{
			close(pstmDel);
			close(pstmCreate);
			close(conn);
		}
	}
	
}
